# -*- coding: utf8 -*-
import sys, time

from soccerbots.net import Client as NetClient
from soccerbots.newgui.interface import SoccerBotsGUI
from soccerbots.ai_lluis import AI

from structs import *

class Client:
    def __init__(self):
        # Init network engine
        self.net_client = None
      
        # Parameters
        self.ai = AI()
        self.round = 1
        self.last_time = 0
        self.first = False
        self.counter = (0,0)

        # Init & Start GUI
        self.gui = SoccerBotsGUI()
        self.gui.setCallback(self.gui_callback)
        self.gui.start()
        print 'Gui started !'
        
        self.gui.join()
        self.net_client.finalize()
        sys.exit(0)

    def fillState(self, state):
        state.round = self.round
        state.teamA.goals = self.counter[0]
        state.teamB.goals = self.counter[1]
        try:
            self.last_time = state.time
        except:
            state.time = self.last_time

    def initStateReceived(self, equip, atacant, state):
        self.equip = equip
        self.fillState(state)
        state.round = self.round
        self.gui.newState(state)

    def stateReceived(self, state):
        self.fillState(state)
        self.gui.newState(state, False)

        movements = self.ai.processState(state, self.equip)
        movements.time = self.last_time
        self.net_client.sendMovements(movements)

    def updateCounter(self, counter):
        self.counter = counter

    def newRound(self):
        self.round += 1
    
    def gui_callback(self, event):
        if event.type == GUIEvent.CONNECT:
            print 'Connecting to server'
            self.net_client = NetClient(self, event.data, 10000)
            self.net_client.connect()
            self.ai.setMaxLinearVel(self.net_client.max_lin_vel)
            self.ai.setMaxAngularVel(self.net_client.max_ang_vel)
            self.net_client.start()

        elif event.type == GUIEvent.INICI:
            if not self.first:
                print 'Sending INICIA event'
                self.net_client.inicia()
                self.first = True
            else:
                print 'Sending XIULET event'
                self.net_client.xiulet()

        elif event.type == GUIEvent.GOAL:
            print 'Sending GOAL event'
            self.net_client.goal()

        elif event.type == GUIEvent.FAULT:
            print 'Sending FAULT event'
            self.net_client.fault(event.fault, event.team)

        elif event.type == GUIEvent.FIPART:
            print 'Sending FIPART event'
            self.net_client.fiPart()

        elif event.type == GUIEvent.FIPARTIT:
            print 'Sending FIPARTIT event'
            self.net_client.fiPartit()
